import os
import sys
import threading
import subprocess

config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'config.ini')
hiburntool = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'HiBurnCmdLine')
images_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'images')

sys.path.append(hiburntool)

def get_config():
    if os.path.exists(config_path):
        with open(config_path, 'r', encoding="utf8") as f:
            config = f.readlines()
            config = [x.strip() for x in config]
    else:
        com_port = input("Please input COM port: ")
        server_ip = input("Please input Server IP: ")
        ip_addr = input("Please input IP address: ")
        netmask = input("Please input NetMask: ")
        gateway = input("Please input GateWay: ")
        config = [com_port, server_ip, ip_addr, netmask, gateway]
        with open(config_path, "w", encoding="utf8") as f:
            for i in config:
                f.write(i + ' \n')
    return config


def reboot_device():
    cmd = ['hdc', 'list', 'targets']
    process = subprocess.Popen(cmd,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.STDOUT,
                               encoding='utf-8')
    if "[Empty]" in process.stdout.read():
        print("No device found")
        return
    cmd = ['hdc', 'shell', 'reboot']
    process = subprocess.Popen(cmd,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.STDOUT,
                               encoding='utf-8')
    if "[Fail]ExecuteCommand need connect-key?" in process.stdout.read():
        print("Please connect device")
        return
    print("Reboot device, please wait...")


def burn_device(config, **kwargs):
    if not os.path.exists(hiburntool):
        print("No Burn Tool")
        return
    if not os.path.exists(images_path):
        print("No Images")
        return
    cmd = [f"{hiburntool}\\jre\\bin\\java.exe", "-jar", f"{hiburntool}\\hiburn.jar", "--burn", "-n", "hi3516dv300", "-m", "net"]
    cmd += config
    cmd += ["69","-x", f"{images_path}\\Hi3516DV300-emmc.xml"]
    print(" ".join(cmd))
    process = subprocess.Popen(cmd,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.STDOUT,
                               encoding='gbk',
                               **kwargs)
    for line in iter(process.stdout.readline, ''):
        print(line)


def main():
    config = get_config()
    th1 = threading.Thread(target=burn_device, args=(config,))
    th2 = threading.Thread(target=reboot_device)
    th1.start()
    th2.start()
    th1.join()
    th2.join()


if __name__ == '__main__':
    main()
